<template>
  <div>
    <!-- 卡片主体 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" @click="dialogVisible = true"
          >＋添加</el-button
        >
      </div>
      <!-- table -->
      <el-table :data="records" style="width: 100%">
        <el-table-column prop="index" label="序号" width="180" type="index">
        </el-table-column>
        <el-table-column prop="tmName" label="品牌名称" width="180">
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" alt="坏了" style="width: 150px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              icon="el-icon-edit"
              @click="modification(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteOne(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3, 6, 9, 12]"
        :page-size="limit"
        layout=" prev, pager, next, sizes,jumper,total"
        :total="total"
      >
      </el-pagination>
      <!-- 弹框 -->
      <el-dialog
        :title="(trademark.logoUrl ? '修改' : '添加') + '商品'"
        :visible.sync="dialogVisible"
        width="35%"
        :before-close="handleClose"
      >
        <!-- 表单 -->
        <el-form
          ref="form"
          :model="trademark"
          label-width="80px"
          :rules="rules"
        >
          <el-form-item label="商品名称" prop="tmName">
            <el-input v-model="trademark.tmName"></el-input>
          </el-form-item>
          <!--
            图片上传组件
              action 上传的服务器地址
                action="http://39.98.123.211/admin/product/fileUpload"
                action="/dev-api/admin/product/fileUpload" 走代理服务器，转发目标服务器
                :action="`${process.env.VUE_APP_BASE_API}/admin/product/fileUpload`"
              show-file-list 是否可以上传多张图片
              on-success 上传图片成功触发回调
                最终得到图片在线地址，想办法显示
              before-upload 上传之前触发的回调
                限制图片大小和格式
              accept 可以接受上传文件的格式
          -->
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              :action="`${baseAPI}/admin/product/fileUpload`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              accept="image/jpeg,image/png"
            >
              <img
                v-if="trademark.logoUrl"
                :src="trademark.logoUrl"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
        </el-form>

        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addGoods">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  reqGetTrademarkList,
  reqDeleteTrademark,
  reqSaveTrademark,
  reqUpdateTrademark,
} from "../../../api/trademark";

export default {
  name: "Trademark",
  data() {
    return {
      //当前地址
      baseAPI: process.env.VUE_APP_BASE_API,
      currentPage: 1,
      total: 0,
      records: [],
      limit: 3,
      id: 0,
      dialogVisible: false,
      isAdjunction: true,
      trademark: {
        tmName: "",
        logoUrl: "",
      },
      // 表单校验规则
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
        ],
        logoUrl: [
          { required: true, message: "请上传品牌LOGO", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.getTrademarkList(this.currentPage, this.limit);
  },
  methods: {
    //请求每页数据
    async getTrademarkList(currentPage, limit) {
      let res = await reqGetTrademarkList(currentPage, limit);
      this.records = res.records;
      this.total = res.total;
    },
    //每页条数发生改变
    handleSizeChange(val) {
      let max = Math.ceil(this.total / val);

      if (this.currentPage > max) {
        this.currentPage = max;
      }
      this.limit = val;
      this.getTrademarkList(this.currentPage, val);
    },
    //页码发生改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTrademarkList(val, this.limit);
    },
    //删除数据
    deleteOne(row) {
      // console.log(row);
      this.$confirm(`此操作将永久删除 ${row.tmName} 文件, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log(row.id);
          await reqDeleteTrademark(row.id);
          if (this.records.length === 1 && this.currentPage > 1) {
            this.currentPage--;
          }
          await this.getTrademarkList(this.currentPage, this.limit);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //弹窗
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 上传成功触发的回调
    handleAvatarSuccess(res) {
      // console.log(res, file);
      console.log(res.data);
      this.trademark.logoUrl = res.data;
      // this.imageUrl = URL.createObjectURL(file.raw);
      // 清空图片表单校验结果
      this.$refs.form.clearValidate(["logoUrl"]);
    },
    // 上传之前触发的回调
    beforeAvatarUpload(file) {
      // file 上传的图片文件信息
      // file.type 文件类型
      const validFileType = ["image/jpeg", "image/jpg", "image/png"];
      const isValidFileType = validFileType.indexOf(file.type) > -1;
      // file.size 文件大小
      const isLt = file.size / 1024 < 500;

      if (!isValidFileType) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt) {
        this.$message.error("上传头像图片大小不能超过 500KB!");
      }
      // 返回值 true 可以上传
      // 返回值 false 不会上传
      return isValidFileType && isLt;
    },
    //addGoods 添加/修改 发送请求
    async addGoods() {
      let { logoUrl, tmName } = this.trademark;
      if (this.isAdjunction) {
        if (logoUrl && tmName) {
          try {
            await reqSaveTrademark(tmName, logoUrl);
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.getTrademarkList(this.currentPage, this.limit);
          } catch (error) {
            this.$message("添加失败");
          }
        }
      } else {
        this.isAdjunction = true;
        if (logoUrl && tmName) {
          try {
            await reqUpdateTrademark({ tmName, logoUrl, id: this.id });

            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getTrademarkList(this.currentPage, this.limit);
          } catch (error) {
            this.$message("修改失败");
          }
        }
      }
      this.dialogVisible = false;
    },

    //修改按钮
    modification(row) {
      this.isAdjunction = false;
      this.trademark.logoUrl = row.logoUrl;
      this.trademark.tmName = row.tmName;
      this.dialogVisible = true;
      this.id = row.id;
    },
  },
  watch: {
    //监视弹出窗的状态隐藏时将数据清空
    dialogVisible(newVal) {
      if (!newVal) {
        this.trademark.logoUrl = "";
        this.trademark.tmName = "";
      }
    },
  },
};
</script>

<style scoped>
.box-card {
  margin: 10px;
}
.el-pagination {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>